package com.wuming.caiwu.filter;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CompFormAuthenticationFilter extends FormAuthenticationFilter {

    final static Logger logger = LoggerFactory.getLogger(CompFormAuthenticationFilter.class);
    private boolean enableDebug = false;

    /**
     * 重写登录地址
     */
    protected void redirectToLogin(ServletRequest requests,
                                   ServletResponse responses) throws IOException {
        HttpServletRequest request = (HttpServletRequest) requests;
        HttpServletResponse response = (HttpServletResponse) responses;


        // 已登陆则 跳到首页
        String reqUrl = request.getRequestURI();
        logger.error(reqUrl);
        //String contextPath = request.getContextPath();
        String loginUrl = "/login_new.jsp";
        if (reqUrl.indexOf("/web/") >= 0) {
            loginUrl = "/login_new.jsp";
        } else if (reqUrl.indexOf("/wx/") >= 0) {
            /******************微信认证 start******************/
            // 请求的路径
            String contextPath = request.getContextPath();
            String param = request.getQueryString();
            if (param != null) {
                reqUrl += "?" + param;
            }
            try {
                reqUrl = java.net.URLEncoder.encode(reqUrl.replace(contextPath, ""), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (enableDebug) {
                response.sendRedirect(contextPath + "/oauth2/oauth2test.htmls?resultUrl=" + reqUrl);//开发时仅用
            } else {
                response.sendRedirect(contextPath + "/oauth2/oauth2.htmls?resultUrl=" + reqUrl);
            }
            return;
            /****************微信认证 start********************/


        }
        WebUtils.issueRedirect(request, response, loginUrl);
    }

    public boolean isEnableDebug() {
        return enableDebug;
    }

    public void setEnableDebug(boolean enableDebug) {
        this.enableDebug = enableDebug;
    }
}